//
//  DataItem.m
//  KG
//
//  Created by Eugene Braginets on 27.03.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DataItem.h"

@implementation DataItem
@synthesize name=_name;
@synthesize itemid=_temid;
@synthesize image=_image;
@synthesize imageAddr=_imageAddr;
@synthesize title=_title;
@synthesize subtitle=_subtitle;
@synthesize coordinate=_coordinate;
@synthesize urlstring=_urlstring;
@synthesize text=_text;
@synthesize objectid=_objectid;
@synthesize value=_value;

- (void)loadImage: (CGSize) size {
    
    //    int ind=[index intValue];
    
    if (self.image) {
        NSLog (@"image is already loaded for name:%@ itemId: %@",self.name,self.itemid);
        return;   
    }
    else {
        NSLog (@"loading image for name:%@ and itemId: %@",self.name,self.itemid);
    }
    
    NSString *imageAddr=[NSString stringWithString:self.imageAddr];
    
    NSLog (@"ImageUrl: %@", imageAddr);
    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageAddr]];
    UIImage* image = [[UIImage alloc] initWithData:imageData];
    
    [self setImage:image];
    //    float width=image.size.width;
    //    float height=image.size.height;
    //    float ratio=width/height;
    //
    //    
    [self setImage:[self scale:image toSize:size]];
    //        
    [[NSNotificationCenter defaultCenter]
     postNotificationName:self.objectid
     object:nil];
}

- (UIImage *)scale:(UIImage *)image toSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

-(void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.value forKey:@"Value"];
}

-(id)initWithCoder:(NSCoder *)decoder
{
    self.value = [decoder decodeObjectForKey:@"Value"];
    return self;
}
@end
